#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>

void signal_handler(int sig)
{
    switch (sig)
    {
    case SIGINT:
        printf("收到INT信号\n");
        break;
    case SIGTERM:
        printf("收到TERM信号, 退出\n");
        exit(EXIT_SUCCESS);
        break;
    case SIGCHLD:
        printf("收到CHLD信号, 回收子进程\n");
        int child_result;
        pid_t child_pid = wait(&child_result);
        printf("子进程%d退出, 结果%d, 回收成功\n", child_pid, child_result);
        break;
    default:
        break;
    }
}

int main(int argc, char const *argv[])
{
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGCHLD, signal_handler);

    pid_t subprocess;

    subprocess = fork();

    if (subprocess < 0)
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if (subprocess == 0)
    {
        // 这个分支只有子进程会执行
        printf("我是子进程\n");
        // 希望子进程启动另外一个程序
        char *argv[] = {
            "ping",
            "-c",
            "10",
            "www.baidu.com",
            NULL};
        int result = execve("/usr/bin/ping", argv, __environ);
        if (result < 0)
        {
            perror("result");
        }
    }
    else
    {
        // pid >0的情况，这个分支由父进程执行
        printf("我是父进程, 子进程pid为: %d\n", subprocess);
        int n = 0;
        while (1)
        {
            printf("模拟父进程运行%d\n", n);
            sleep(1);
        }
    }
    return 0;
}
